package cn.wolfcode.crm.service.imp;

import cn.wolfcode.crm.domain.Client;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.RechargeItem;
import cn.wolfcode.crm.mapper.ClientMapper;
import cn.wolfcode.crm.mapper.RechargeItemMapper;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.query.RechargeItemQueryObject;
import cn.wolfcode.crm.service.IRechargeItemService;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class RechargeItemServiceImpl implements IRechargeItemService {
    @Autowired
    private RechargeItemMapper rechargeItemMapper;
    @Autowired
    private ClientMapper clientMapper;


    public void delete(Long id) {
        rechargeItemMapper.deleteByPrimaryKey(id);
    }

    public RechargeItem selectByPrimaryKey(Long id) {
        return rechargeItemMapper.selectByPrimaryKey(id);
    }

    public List<RechargeItem> selectAll() {
        return rechargeItemMapper.selectAll();
    }

    public PageResult query(RechargeItemQueryObject qo) {
        int total = rechargeItemMapper.selectCount(qo);
        if (total == 0) {
            return new PageResult(total, Collections.EMPTY_LIST);
        }
        List<RechargeItem> rows = rechargeItemMapper.queryForList(qo);
        return new PageResult(total, rows);
    }



    public void recharge(RechargeItem rechargeItem) {
        //设定为充值操作
        rechargeItem.setOperation(1);
        //执行操作的员工
        Employee currentUser = UserContext.getCurrentUser();
        rechargeItem.setOpUser(currentUser);
        //计算充值后金额
        BigDecimal addincome = rechargeItem.getAddincome();
        BigDecimal income = rechargeItem.getIncome();
        BigDecimal afterBalance = rechargeItem.getBeforeBalance().add(addincome).add(income).setScale(2, RoundingMode.HALF_UP);
        rechargeItem.setAfterBalance(afterBalance);
        //充值时间
        rechargeItem.setOptime(new Date());
        //会员的金额要增加
        Client client = rechargeItem.getClient();
        clientMapper.updateBalance(client.getId(),afterBalance);
        //保存充值明细
        rechargeItemMapper.insert(rechargeItem);



    }

    public BigDecimal getTotalExpense() {
        return rechargeItemMapper.getTotalExpense();
    }

    public Integer getTotalCount() {
        return rechargeItemMapper.getTotalCount();
    }

    public List<Map<String,Object>> getTOP() {
        return rechargeItemMapper.getTOP();
    }
}
